package com.zzhou.linkinfo.clock.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.StringUtils;
import com.zzhou.linkinfo.clock.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * PictureSelector for clock release task
 * Created by Carlos on 2019/3/14.
 */
public class ClockShowPicsAdapter extends BaseAdapter {
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;
    private LayoutInflater mInflater;
    private List<LocalMedia> mSelectedList = new ArrayList<>();
    private int mSelectMax = 9;
    /**
     * 点击添加图片跳转
     */
    private IAddPicClickListener mOnAddPicClickListener;

    public interface IAddPicClickListener {
        void onAddPicClick();

        void updateMainView();
    }

    public ClockShowPicsAdapter(Context context, IAddPicClickListener mOnAddPicClickListener) {
        super(context);
        mInflater = LayoutInflater.from(context);
        this.mOnAddPicClickListener = mOnAddPicClickListener;
    }

    public void setSelectMax(int mSelectMax) {
        this.mSelectMax = mSelectMax;
    }

    public void setList(List<LocalMedia> list) {
        this.mSelectedList = list;
    }

    public class ViewHolder extends BaseViewHolder {

        ImageView selectedImg;
        LinearLayout imgDelView;
        TextView durationView;

        public ViewHolder(View view) {
            super(view);
            selectedImg = view.findViewById(R.id.fiv);
            imgDelView = view.findViewById(R.id.ll_del);
            durationView = view.findViewById(R.id.tv_duration);
        }

        @Override
        public void setData(int position) {
            //少于8张，显示继续添加的图标
            if (getItemViewType(position) == TYPE_CAMERA) {
                selectedImg.setImageResource(R.drawable.clock_add_img);
                selectedImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnAddPicClickListener.onAddPicClick();
                    }
                });
                imgDelView.setVisibility(View.INVISIBLE);
            } else {
                imgDelView.setVisibility(View.VISIBLE);
                imgDelView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int index = getAdapterPosition();
                        // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                        // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
                        if (index != RecyclerView.NO_POSITION) {
                            mSelectedList.remove(index);
                            notifyItemRemoved(index);
                            notifyItemRangeChanged(index, mSelectedList.size());

                            if (mSelectedList.size() == 0) {
                                mOnAddPicClickListener.updateMainView();
                            }
                        }
                    }
                });
                LocalMedia media = mSelectedList.get(position);
                int mimeType = media.getMimeType();
                String path = "";
                if (media.isCut() && !media.isCompressed()) {
                    // 裁剪过
                    path = media.getCutPath();
                } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                    // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                    path = media.getCompressPath();
                } else {
                    // 原图
                    path = media.getPath();
                }
                // 图片
                if (media.isCompressed()) {
                    Log.i("compress image result:", new File(media.getCompressPath()).length() / 1024 + "k");
                    Log.i("压缩地址::", media.getCompressPath());
                }

                Log.i("原图地址::", media.getPath());
                int pictureType = PictureMimeType.isPictureType(media.getPictureType());
                if (media.isCut()) {
                    Log.i("裁剪地址::", media.getCutPath());
                }
                long duration = media.getDuration();
                durationView.setVisibility(pictureType == PictureConfig.TYPE_VIDEO
                        ? View.VISIBLE : View.GONE);
                if (mimeType == PictureMimeType.ofAudio()) {
                    durationView.setVisibility(View.VISIBLE);
                    Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.picture_audio);
                    StringUtils.modifyTextViewDrawable(durationView, drawable, 0);
                } else {
                    Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.video_icon);
                    StringUtils.modifyTextViewDrawable(durationView, drawable, 0);
                }
                durationView.setText(DateUtils.timeParse(duration));
                if (mimeType == PictureMimeType.ofAudio()) {
                    selectedImg.setImageResource(R.drawable.audio_placeholder);
                } else {
                    RequestOptions options = new RequestOptions()
                            .centerCrop()
                            .placeholder(R.color.clock_color_f6)
                            .diskCacheStrategy(DiskCacheStrategy.ALL);
                    Glide.with(itemView.getContext())
                            .load(path)
                            .apply(options)
                            .into(selectedImg);
                }
                //itemView 的点击事件
                if (mItemClickListener != null) {
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int adapterPosition = getAdapterPosition();
                            mItemClickListener.onItemClick(adapterPosition, v);
                        }
                    });
                }
            }
        }

        private int getItemViewType(int position) {
            if (isShowAddItem(position)) {
                return TYPE_PICTURE;
            } else {
                return TYPE_PICTURE;
            }
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.clock_release_filter_image, parent, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowAddItem(position)) {
            return TYPE_PICTURE;
        } else {
            return TYPE_PICTURE;
        }
    }

    private boolean isShowAddItem(int position) {
        int size = mSelectedList.size() == 0 ? 0 : mSelectedList.size();
        return position == size;
    }

    @Override
    public int getItemCount() {
        return mSelectedList.size();
    }

    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position, View v);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }
}
